package com.example.restful.controller;

import com.example.restful.api.ExceptionMsg;
import com.example.restful.api.Response;
import com.example.restful.api.ResponseData;
import com.example.restful.bean.Article;
import com.example.restful.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    ArticleController
 * Author:      AmbroseCdMeng
 * Date:        2021/2/119:19
 * Description: 实现数据 CRUD 的控制器，并实现数据返回
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    protected Response result(ExceptionMsg msg){
        return new Response(msg);
    }

    protected Response result(){
        return new Response();
    }

    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseData getArticleList(){
        List<Article> list = new ArrayList<>(articleRepository.findAll());
        return new ResponseData(ExceptionMsg.SUCCESS, list);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public ResponseData add (Article article){
        boolean isSuccess = articleRepository.save(article);
        return new ResponseData(isSuccess ? ExceptionMsg.SUCCESS : ExceptionMsg.FAILED, article);
    }

    @RequestMapping(value = "/", method = RequestMethod.DELETE)
    public ResponseData delete(@PathVariable("id") long id){
        boolean isSuccess = articleRepository.deleteById(id);
        return new ResponseData(isSuccess ? ExceptionMsg.SUCCESS : ExceptionMsg.FAILED, "");
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    public ResponseData update(Article article){
        boolean isSuccess = articleRepository.save(article);
        return new ResponseData(isSuccess ? ExceptionMsg.SUCCESS : ExceptionMsg.FAILED, article);
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseData findArticle(@PathVariable("id") Integer id){
        Article article = articleRepository.findById();
        if (article != null){
            return new ResponseData(ExceptionMsg.SUCCESS, article);
        }
        return new ResponseData(ExceptionMsg.FAILED, null);
    }
}
